﻿using System;
using Apache.Cassandra;
using Thrift.Protocol;
using Thrift.Transport;

namespace Sandy.Connections
{
    /// <summary>
    /// Represents a connection to a Cassandra server.
    /// Connections are best handled by SandyClient (just use one of its constructors).
    /// </summary>
    public class Connection
    {
        private TTransport _transport;
        private Cassandra.Client _client;

        /// <summary>
        /// Create a new connection (TBufferedTransport) to a given host and port.
        /// </summary>
        /// <param name="host">The hostname to connect to</param>
        /// <param name="port">The port to use (default: 9160)</param>
        public Connection(string host, int port = 9160)
        {
            Created = DateTime.Now;

            _transport = new TBufferedTransport(new TSocket(host, port), 64 * 1024);
            _client = new Cassandra.Client(new TBinaryProtocol(_transport));

            _transport.Open();
        }

        /// <summary>
        /// The time at which this connection was created
        /// </summary>
        public DateTime Created { get; private set; }

        /// <summary>
        /// The associated client on which to query.
        /// </summary>
        public Cassandra.Client CassandraClient
        {
            get { return _client; }
        }

        /// <summary>
        /// Is the connection Open?
        /// </summary>
        public bool IsOpen { get { return _transport.IsOpen; } }

        /// <summary>
        /// Close the transport and disconnect from the server.
        /// </summary>
        public void Close()
        {
            _transport.Close();
        }
    }
}
